package com.easy.carl.algorithm.hashMap;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName CanConstruct383
 * @Description 383. 赎金信
 * @Author zheng
 * @Date 2021/12/21 11:24
 * @Version 1.0
 **/
public class CanConstruct383 {
    /**
     * @return boolean
     * @Description 383. 赎金信 map法效率低
     * @Date 2021/12/21 15:21
     * @Param [ransomNote, magazine]
     **/
    public boolean canConstruct1(String ransomNote, String magazine) {
        if (magazine.length() < ransomNote.length()) {
            return false;
        }
        Map<Character, Integer> map = new HashMap<>(16);
        for (char c : magazine.toCharArray()) {
            map.put(c, map.getOrDefault(c, 0) + 1);
        }
        for (char c : ransomNote.toCharArray()) {
            if (map.getOrDefault(c, 0) > 0) {
                map.put(c, map.get(c) - 1);
            } else {
                return false;
            }
        }
        return true;
    }

    /**
     * @return boolean
     * @Description 数组法
     * @Date 2021/12/21 15:27
     * @Param [ransomNote, magazine]
     **/
    public boolean canConstruct(String ransomNote, String magazine) {
        int[] arr = new int[26];
        for (char c : magazine.toCharArray()) {
            int index = c - 'a';
            arr[index] = ++arr[index];
        }
        for (char c : ransomNote.toCharArray()) {
            int index = c - 'a';
            if (arr[index] > 0) {
                arr[index] = --arr[index];
            } else {
                return false;
            }
        }
        return true;
    }

    public static void main(String[] args) {
        CanConstruct383 canConstruct383 = new CanConstruct383();
        System.out.println(canConstruct383.canConstruct("aa", "aab"));
    }

}
